package cn.tjad.tjad2.module.common.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.qiandian.android.base.fragment.BaseFragment;

import cn.tjad.tjad2.consts.Keys;

public class FragmentContainer extends BaseFragment {

    private FrameLayout container;
    private FragmentManager fragmentManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getChildFragmentManager();
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        container = new FrameLayout(getContext());
        container.setId(container.hashCode());
        return container;
    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        Bundle bundle = getArguments();
        String pageId = null;
        Bundle args = null;
        String title = null;
        if (bundle != null) {
            pageId = bundle.getString(Keys.PAGE_ID);
            args = bundle.getBundle(Keys.PAGE_ARGS);
        }
        if (pageId != null) {
            addFragment(pageId, args);
        }
        return view;
    }

    public void addFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(container.getId(), fragment);
        transaction.addToBackStack(fragment.getClass().getSimpleName());
        transaction.commit();
    }

    public void addFragment(String pageId, Bundle args) {
        Fragment fragment = (Fragment) ARouter.getInstance().build(pageId).navigation();
        if (fragment != null) {
            fragment.setArguments(args);
            addFragment(fragment);
        }
    }

    @Override
    public boolean interceptBackPressed() {
        int count = fragmentManager.getBackStackEntryCount();
        if (count > 1) {
            fragmentManager.popBackStack();
            return true;
        } else {
            return super.interceptBackPressed();
        }
    }
}
